package com.dwxt.cdms.service;

import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.dao.BirthdayMapper;
import com.dwxt.cdms.entity.Birthday;
import com.dwxt.cdms.entity.BirthdayExample;
import com.dwxt.cdms.entity.Customer;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.YesOrNo;
import com.dwxt.common.util.JsonUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class BirthdayService {

    @Autowired
    private BirthdayMapper birthdayMapper;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private StationService stationService;

    public BaseResult page(Page page, Birthday birth) {
        Integer stationId = stationService.getLoginUserStation();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        BirthdayExample example = new BirthdayExample();
        example.setStationId(stationId);
        Optional.ofNullable(birth).map(Birthday::getIsHandle).ifPresent(isHandle -> {
            example.createCriteria().andIsHandleEqualTo(isHandle);
        });
        List<Birthday> birthdays = birthdayMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo(birthdays);
        List<HashMap> customerList =
                birthdays.stream().map(birthday -> {
                    Customer customer = customerService.selectCustomerById(birthday.getCustomerId());
                    HashMap hashMap = JsonUtils.jsonToPojo(JsonUtils.objectToJson(customer), HashMap.class);
                    hashMap.put("isHandle", birthday.getIsHandle());
                    hashMap.put("id", birthday.getId());
                    hashMap.put("birth", birthday.getMonth() + "/" + birthday.getDay());
                    return hashMap;
                }).collect(Collectors.toList());
        pageInfo.setList(customerList);
        return BaseResult.ok(pageInfo);
    }

    public BaseResult handle(Integer id) {
        Birthday birthday = new Birthday();
        birthday.setId(id);
        birthday.setIsHandle(YesOrNo.YES);
        birthdayMapper.updateByPrimaryKeySelective(birthday);
        return BaseResult.ok();
    }
}
